#include "comp.h"


/* Use Comparator 1 for single bound hysterisis control */
void comp_init(void)
{
	GPIO_InitTypeDef myGPIO_comp1;
	COMP_InitTypeDef myCOMP_struct;	
	EXTI_InitTypeDef myEXTI_comp1;
	NVIC_InitTypeDef myNVIC_comp1;
	
	//Enable the SYSCFG APB clock to get write access to comparator register 
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

	//Configure the comparator input (PA1) in analog mode

	myGPIO_comp1.GPIO_Pin=GPIO_Pin_1; 
	myGPIO_comp1.GPIO_Mode=GPIO_Mode_AN;
	myGPIO_comp1.GPIO_Speed=GPIO_Speed_Level_3;
	myGPIO_comp1.GPIO_OType=GPIO_OType_PP;
	myGPIO_comp1.GPIO_PuPd=GPIO_PuPd_NOPULL;
	
	GPIO_Init(GPIOA, &myGPIO_comp1);
		
	/* No need to configure comparator output since only interrupt is needed */
	
	//Configure the comparator, using COMP1, DAC1 as inverting input, medium hysteresis level and high speed

	myCOMP_struct.COMP_InvertingInput=COMP_InvertingInput_DAC1;
	myCOMP_struct.COMP_Output=COMP_Output_None;
	myCOMP_struct.COMP_OutputPol=COMP_OutputPol_NonInverted;
	myCOMP_struct.COMP_Hysteresis=COMP_Hysteresis_Medium;
	myCOMP_struct.COMP_Mode=COMP_Mode_HighSpeed;

	COMP_Init(COMP_Selection_COMP1, &myCOMP_struct);

	//Enable the comparator
	COMP_Cmd(COMP_Selection_COMP1, ENABLE);
	
	//Enable and configure the comp interrupt, Rising edige(optional),mode is interrupt

	myEXTI_comp1.EXTI_Line=EXTI_Line21;
	myEXTI_comp1.EXTI_Mode=EXTI_Mode_Interrupt;
	myEXTI_comp1.EXTI_Trigger=EXTI_Trigger_Falling;
	myEXTI_comp1.EXTI_LineCmd=ENABLE;

	EXTI_Init(&myEXTI_comp1);
	
	//Enable the comparator interrupt vector 

	myNVIC_comp1.NVIC_IRQChannel = ADC1_COMP_IRQn ;
	myNVIC_comp1.NVIC_IRQChannelPriority = 0;
	myNVIC_comp1.NVIC_IRQChannelCmd=ENABLE;

	// Interrupt priority  NVIC_PriorityGroupConfig()
	NVIC_Init(&myNVIC_comp1);
}

